package com.app.backend.common.serviceImpl;

import com.alibaba.fastjson.JSONObject;
import com.app.backend.common.service.RedisValueService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @program: RedisValueServiceImpl
 * @description: redis value操作类实现
 * @author: Zhun.Xiao
 * @create: 2018-10-29 16:14
 **/
@Service
public class RedisValueServiceImpl<T> implements RedisValueService<T> {

    @Resource
    protected RedisTemplate<String, T> redisTemplate;


    @Resource
    protected ValueOperations valueOperations;


    @Override
    public Long incr(String redisKey, Long delta, Long expire) {
        Long value = valueOperations.increment(redisKey, delta);
        if (expire != -1) {
            redisTemplate.expire(redisKey, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    @Override
    public void set(String redisKey, T value, long expire) {
        valueOperations.set(redisKey, value);
        if (expire != -1) {
            redisTemplate.expire(redisKey, expire, TimeUnit.SECONDS);
        }
    }

    @Override
    public void expire(String redisKey, T value, long expire) {
        if (expire != -1) {
            redisTemplate.expire(redisKey, expire, TimeUnit.SECONDS);
        }
    }


    @Override
    public void remove(String redisKey) {
        redisTemplate.delete(redisKey);
    }

    @Override
    public T get(String redisKey) {
        return (T) valueOperations.get(redisKey);

    }

    @Override
    public <T extends Object> T get(String redisKey, Class<T> targetClass) {
        Object object = get(redisKey);
        T t = JSONObject.parseObject(object.toString(), targetClass);
        return t;
    }

    @Override
    public T getAndSet(String redisKey, T value) {
        return (T) valueOperations.getAndSet(redisKey, value);
    }


}
